package com.edu.jsu.commonutils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * JWT工具类
 * @author 廖俊杰
 * @version 1.0
 * @date 2021/12/1 13:51
 */
public class JwtUtils {

    /**
     * token过期时间
     */
    public static final long EXPIRE = 1*60*60*24;

    /**
     * 秘钥
     */
    public static final String APP_SECRET = "wetHIUH29ewt81HIUHclxbibgeo";

    /**
     * 生成token字符串
     * @param id 用户id
     * @param nickname 用户昵称
     * @return
     */
    public static String getJwtToken(String id,String nickname){
        String jwtToken = Jwts.builder()
                //设置token的头信息
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //设置token的过期时间
                .setSubject("onlinecourse-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                //设置token的主体部分,存储用户信息
                .claim("id",id)
                .claim("nickname",nickname)
                .signWith(SignatureAlgorithm.HS256,APP_SECRET)
                .compact();

        return jwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken token字符串
     * @return
     */
    public static boolean checkToken(String jwtToken){
        if (StringUtils.isEmpty(jwtToken)) {
            return false;
        }

        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        }catch (SignatureException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断请求中token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if (StringUtils.isEmpty(jwtToken)) {
                return false;
            }
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        }catch (SignatureException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据请求中的token获取用户id
     * @param request
     * @return
     */
    public static String getUserIdByToken(HttpServletRequest request){
        String jwtToken = request.getHeader("token");
        if (StringUtils.isEmpty(jwtToken)) {
            return "";
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();

        return (String)claims.get("id");
    }
}
